<template>
  <a @click="dialog = true">
    <span>文件</span>
    <a-modal v-model="dialog" @ok="submit" width="900px" :closable="false">
      <div>
        <p class="flex justify-end"></p>
        <p class="flex justify-end">
          <a-button type="primary" @click="showupload">上传文件</a-button>
          <a-modal v-model="show" title="上传文件" @ok="closeupload" @cancel="closeupload">
            <a-form ref="form">
              <a-form-item label="文件类型：">
                <a-radio-group v-model="form.type">
                  <a-radio v-for="i in type" :key="i" :value="i">
                    {{ i }}
                  </a-radio>
                  <a-input style="width:120px" :disabled="form.type != 'Others'" v-model="other"></a-input>
                </a-radio-group>
              </a-form-item>
            </a-form>
            <p>支持扩展名：.doc、.docx、.pdf、.xlsx、.xls、image</p>
            <a-upload :showUploadList="false" :customRequest="upload" accept=".doc,.docx,.pdf,.xlsx,.xls,image/*">
              <a-button :loading="uploading" type="primary"> <a-icon type="upload" /> Upload </a-button> </a-upload
            ><br />
            <div>
              <a-tag v-for="item in filename" :key="item" color="blue">
                {{ item }}
              </a-tag>
            </div>
          </a-modal>
          <!-- <a-upload :showUploadList="false" :customRequest="upload" accept=".doc,.docx,.pdf,.xlsx,.xls,image/*">
            <a-button :loading="uploading" type="primary">上传文件</a-button>
          </a-upload> -->
        </p>
        <br />
        <a-table rowKey="id" :columns="columns" :data-source="data">
          <span slot="updateTime" slot-scope="updateTime"> {{ humanizeDate(updateTime) }}</span>
          <template slot="opt" slot-scope="text, record">
            <a @click="download(record)">查看</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确认删除吗?" @confirm="() => onDelete(record)">
              <a href="javascript:;">删除</a>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </a-modal>
  </a>
</template>
<script>
import { creatFile, getFile, deleteFile } from '@/api/common'
import moment from 'moment'
import OSSClient from '@/utils/oss'
import AvatarModal from '@/views/account/settings/AvatarModal.vue'
const client = new OSSClient()

const columns = [
  { dataIndex: 'ids', key: 'ids', title: '编号' },
  { dataIndex: 'fileName', key: 'fileName', title: '文件名称' },
  { dataIndex: 'fileType', key: 'fileType', title: '文件类型' },
  { dataIndex: 'updateTime', key: 'updateTime', title: '上传日期', scopedSlots: { customRender: 'updateTime' } },
  { dataIndex: 'fileFormat', key: 'fileFormat', title: '文件格式' },
  { dataIndex: 'opt', key: 'opt', title: '操作', scopedSlots: { customRender: 'opt' } }
]
export default {
  components: { AvatarModal },
  name: 'FileDialog',
  props: ['record'],
  data() {
    return {
      count: 0,
      dialog: false,
      data: [],
      columns,
      uploading: false,
      other: '',
      show: false,
      type: ['Drawdown notice', 'Site visit pic', 'invoice', 'QS report', 'Others'],
      form: {
        type: 'Drawdown notice'
      },
      filename: []
    }
  },
  watch: {
    dialog(v) {
      v && this.getData()
    }
  },
  methods: {
    handleChange(info) {
      console.log(1111)
      let fileList = [...info.fileList]
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url
          // file.status = 'done'
        }
        return file
      })
      this.fileList = fileList
    },
    async submit() {
      this.dialog = false
    },
    showupload() {
      this.dialog = false
      this.show = true
    },
    closeupload() {
      this.getData()
      this.form.type = 'Drawdown notice'
      this.filename = []
      this.dialog = true
      this.show = false
    },
    download(record) {
      let suffix = record.fileUrl.split('.').pop()
      if (['doc', 'docx', 'xls', 'xlsx'].includes(suffix)) {
        window.open(`https://view.officeapps.live.com/op/view.aspx?src=${window.encodeURIComponent(record.fileUrl)}`)
      } else {
        window.open(record.fileUrl)
      }
    },
    humanizeDate(v) {
      if (v) {
        return moment(v * 1000).format('YYYY-MM-DD') || '--'
      } else {
        return '-'
      }
    },
    async onDelete(record) {
      await deleteFile(record.id)
      this.getData()
    },
    async getData() {
      let count = 0
      const res = await getFile({
        projectId: this.record.id,
        relationType: 6
      })
      this.data = res?.result?.data || []
      this.data.forEach(el => {
        el.ids = ++count
      })
      // console.log(this.data)
    },
    async upload(obj) {
      try {
        this.uploading = true
        this.filename.push(obj.file.name)
        let url = await client.upload(obj.file, this.record.id, 6)
        await this.createFile(obj.file.name, url)
        this.uploading = false
        this.getData()
        this.$message.success('上传成功')
      } catch (err) {
        console.error(err)
        this.$message.error('上传失败')
      }
    },
    async createFile(filename, url) {
      let [name, suffix] = filename.split('.')
      const data = {
        fileName: name,
        fileType: this.form.type == 'Others' ? this.other : this.form.type,
        fileFormat: suffix,
        projectId: this.record.id,
        relationType: 6,
        fileUrl: url
      }
      return await creatFile(data)
    }
  }
}
</script>
<style lang="scss" scoped></style>
